const request = require('../../utils/request')
const eventBus = require('../../utils/eventBus')

Page({
  data: {
    bookings: [],
    showRatingModal: false,
    currentBooking: null,
    ratingValue: 0,
    commentValue: '',
    scrollHeight: 0
  },

  onLoad() {
    this.fetchBookings()
    eventBus.on('bookingCreated', this.fetchBookings.bind(this))
    
    const systemInfo = wx.getSystemInfoSync()
    const navHeight = 44
    const statusBarHeight = systemInfo.statusBarHeight
    const scrollHeight = systemInfo.windowHeight - (navHeight + statusBarHeight)
    
    this.setData({
      scrollHeight: scrollHeight
    })
  },

  onUnload() {
    eventBus.off('bookingCreated', this.fetchBookings)
  },

  async fetchBookings() {
    try {
      // 获取当前用户ID
      const app = getApp();
      if (!app.globalData.isLoggedIn || !app.globalData.userInfo) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        });
        return;
      }
      const userId = app.globalData.userInfo.id;
      
      const response = await request({
        url: '/api/bookings',
        data: { userId }
      })

      const now = new Date()
      const processedBookings = []
      
      for (let i = 0; i < response.data.length; i++) {
        const booking = response.data[i]
        const timeSlots = booking.course_time.split('-')
        const startTime = timeSlots[0]
        const endTime = timeSlots[1]
        const date = booking.formatted_date
        
        const bookingStartTime = new Date(date.replace(/-/g, '/') + ' ' + startTime)
        const bookingEndTime = new Date(date.replace(/-/g, '/') + ' ' + endTime)
        
        let status = booking.status
        if (status !== 'cancelled') {
          if (now < bookingStartTime) {
            status = 'upcoming'
          } else if (now >= bookingStartTime && now <= bookingEndTime) {
            status = 'ongoing'
          } else {
            status = 'completed'
          }
        }

        const processedBooking = {
          id: booking.id,
          course_id: booking.course_id,
          course_name: booking.course_name,
          formatted_date: booking.formatted_date,
          course_time: booking.course_time,
          teacher_name: booking.teacher_name,
          cover: booking.cover,
          status: status,
          rating: booking.rating || 0,
          comment: booking.comment || '',
          is_rated: booking.is_rated
        }
        
        processedBookings.push(processedBooking)
      }

      this.setData({ bookings: processedBookings })
    } catch (error) {
      console.error('获取预约记录失败:', error)
      wx.showToast({
        title: '获取预约记录失败',
        icon: 'none'
      })
    }
  },

  navigateToCourse(e) {
    const courseId = e.currentTarget.dataset.courseId
    wx.navigateTo({
      url: '/pages/course-detail/index?id=' + courseId
    })
  },

  openRatingModal(e) {
    const booking = e.currentTarget.dataset.booking
    this.setData({
      showRatingModal: true,
      currentBooking: booking,
      ratingValue: 0,
      commentValue: '',
      isEditing: false
    })
  },

  editRating(e) {
    const booking = e.currentTarget.dataset.booking
    this.setData({
      showRatingModal: true,
      currentBooking: booking,
      ratingValue: booking.rating || 0,
      commentValue: booking.comment || '',
      isEditing: true
    })
  },

  async submitRating() {
    if (this.data.ratingValue === 0) {
      wx.showToast({
        title: '请选择评分',
        icon: 'none'
      })
      return
    }

    wx.showLoading({ title: '提交中...' })

    try {
      // 获取当前用户ID
      const app = getApp();
      const userId = app.globalData.userInfo?.id;
      if (!userId) {
        wx.hideLoading();
        wx.showToast({
          title: '登录状态异常',
          icon: 'none'
        });
        return;
      }
      
      const courseId = this.data.currentBooking.course_id

      await request({
        url: '/api/bookings/rate',
        method: 'POST',
        data: {
          bookingId: this.data.currentBooking.id,
          rating: this.data.ratingValue,
          comment: this.data.commentValue,
          isUpdate: this.data.isEditing,
          userId
        }
      })

      await this.fetchBookings()

      this.setData({
        showRatingModal: false,
        currentBooking: null,
        ratingValue: 0,
        commentValue: '',
        isEditing: false
      })

      wx.hideLoading()

      wx.showToast({
        title: '评价成功',
        icon: 'success'
      })

      eventBus.emit('commentUpdated', {
        courseId: courseId
      })
    } catch (error) {
      console.error('评价失败:', error)
      wx.hideLoading()
      wx.showToast({
        title: '评价失败',
        icon: 'none'
      })
    }
  },

  closeRatingModal() {
    this.setData({
      showRatingModal: false,
      currentBooking: null,
      ratingValue: 0,
      commentValue: ''
    })
  },

  onRatingChange(e) {
    this.setData({
      ratingValue: e.detail.value
    })
  },

  onCommentInput(e) {
    this.setData({
      commentValue: e.detail.value
    })
  },

  onBack() {
    wx.navigateBack()
  },

  setRating(e) {
    const rating = parseInt(e.currentTarget.dataset.rating)
    this.setData({
      ratingValue: rating
    })
  }
})